﻿using System.Linq;

using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

[CanEditMultipleObjects]
[CustomEditor(typeof(UGUIAtlas), true)]

public class UGUIAtlasEditor : Editor
{
    public override void OnInspectorGUI()
    {
        GUILayout.Space(3f);
        UGUIEditorTools.SetLabelWidth(80f);
        serializedObject.Update();

        UGUIEditorTools.DrawProperty("Atlas Texture", serializedObject, "texture");
        UGUIEditorTools.DrawProperty("Sprites", serializedObject, "sprites");

        serializedObject.ApplyModifiedProperties();

        UGUIAtlas atlas = serializedObject.targetObject as UGUIAtlas;

        if (GUILayout.Button("Import All Sprites"))
        {
            if (atlas != null)
            {
                Texture texture = atlas.GetTexture();

                if (texture != null)
                {
                    string assetPath = AssetDatabase.GetAssetPath(texture);
                    var assets = AssetDatabase.LoadAllAssetsAtPath(assetPath)
                                              .OfType<Sprite>()
                                              .ToList();
                    UGUIEditorTools.RegisterUndo("Import All Sprites", atlas);
                    atlas.EditorSetSprites(assets);
                    EditorUtility.SetDirty(atlas);
                }
            }
        }
    }

    [MenuItem("Asset Tools/Generate Altas", true)]
    [MenuItem("Assets/Asset Tools/Generate Atlas", true)]
    public static bool ValidateCreateAtlas()
    {
        return (Selection.activeObject != null && (Selection.activeObject is Texture));
    }

    [MenuItem("Asset Tools/Generate Altas")]
    [MenuItem("Assets/Asset Tools/Generate Atlas")]
    public static void CreateAltas()
    {
        string path = AssetDatabase.GetAssetPath(Selection.activeObject);
        var sprs = AssetDatabase.LoadAllAssetsAtPath(path).OfType<Sprite>().ToList();
        string atlasPath = path.Substring(0, path.LastIndexOf(".")) + "Atlas.asset";
        UGUIAtlas atlas = AssetDatabase.LoadAssetAtPath<UGUIAtlas>(atlasPath);
        bool isNew = false;
        if (atlas == null)
        {
            isNew = true;
            atlas = ScriptableObject.CreateInstance<UGUIAtlas>();
        }
        atlas.name = Selection.activeObject.name;
        atlas.EditorSetSprites(sprs);
        atlas.EditorSetTexture(Selection.activeObject as Texture);
        if(isNew)
        {
            AssetDatabase.CreateAsset(atlas, atlasPath);
        }
        else
        {
            EditorUtility.SetDirty(atlas);
        }
    }
}
